<script setup>
import {useRoute} from 'vue-router';
import router from "@/router/index.js";
import useCountdown from "@/hooks/useCountdown.js";
import {formatDateTime, formatPrice} from "@/utils/index.js";
import {getOrderDetails} from "@/api/order.js";
import {applyForAfterSales} from "@/api/afterSale.js";
import useUserStore from '@/store/modules/user'
import useSettingStore from '@/store/modules/setting.js'
const route = useRoute();
import { showToast } from 'vant';
import {useI18n} from 'vue-i18n';

const {t} = useI18n();
const useUser = useUserStore()
const currency = ref(useSettingStore().global.currencySymbol || '')
const refundOnlyReason = ref((useSettingStore().global.refundOnlyReason || []).map(reason => ({label: reason, value: reason})) );
const returnGoodsRefund = ref((useSettingStore().global.returnGoodsRefund || []).map(reason => ({label: reason, value: reason})) );
const uploadImgUrl = ref(import.meta.env.VITE_APP_BASE_API + "/file/upload"); // 上传的图片服务器地址
const orderId = ref(route.query.id) // 订单ID

const form = reactive({
  serviceType: 0,
  reasons: '',
});
form.reasons = refundOnlyReason.value[0]?.value
const showPicker = ref(false)
const serviceTypeList = ref([
  {
    name: t('afterSale.refundOnly'),
    type: 0
  },
  {
    name: t('afterSale.returnGoodsRefund'),
    type: 1
  }
])

// 修改服务类型
const currentServiceType = ref(t('afterSale.refundOnly'))
function changeServiceType(data) {
  const { selectedValues } = data
  form.serviceType = selectedValues[0];
  currentServiceType.value = form.serviceType ? t('afterSale.returnGoodsRefund') : t('afterSale.refundOnly')
  if (form.serviceType) {
    reasonList.value = returnGoodsRefund.value
  } else {
    reasonList.value = refundOnlyReason.value
  }
  showPicker.value = false
  form.reasons = reasonList.value[0].value
}
function selectionReason(data) {
  const { selectedValues } = data
  showReasonPicker.value = false
  form.reasons = selectedValues[0]
}
// 退款原因
const showReasonPicker = ref(false)
const reasonList = ref(refundOnlyReason.value)
const reasonName = {
  text: 'label',
  value: 'value',
  children: null,
};
// 申请成功页面
const skipDisplay = ref(false)
const requestHeaders = {
  Authorization: 'Bearer ' + useUser.token
}
// 上传图片
const fileList = ref([])
const imgUrlList = ref([])
const afterRead = (file) => {
  const formData = new FormData();
  formData.append('file', file.file);
  fetch(uploadImgUrl.value, {
    method: 'POST',
    body: formData,
    headers: requestHeaders,
  }).then(response => response.json()).then(data => {
    imgUrlList.value.push(data.data)
  }).catch(error => {
    console.error('error:', error);
  });
};

function delImg(file) {
  console.log(file, 'file')
}

const serviceTypeName = {
  text: 'name',
  value: 'type',
  children: null,
};

const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = '';
};

// 获取订单详情
const logs = ref([])
const remainingTime = ref('');
const orderDetail = ref({
  logs: [],
  details: []
}) // 订单详情数据
async function getDetailInfo(load) {
  getOrderDetails(orderId.value).then((res) => {
    orderDetail.value = res.data;
    const {status} = res.data
    for (let i = 0; i < stepsData.value.length; i++) {
      let matchedData = orderDetail.value.logs.find(item => item.operateType === stepsData.value[i].type);
      if (matchedData) {
        stepsData.value[i].description = formatDateTime(matchedData.createTime);
      }
    }
    if (status === 0) {
      remainingTime.value = useCountdown(orderDetail.value.time); // 订单倒计时
    } else {
      resumePayment.value = false
      clearTimer()
    }
    // 订单待收货状态获取物流信息
    if (orderDetail.value.status === 2) {
      getLogisticsInformation()
    }
  }).catch(() => {
  })
}

function selectProduct() {
  checkedAll.value = !orderDetail.value.details.some(item => !item.checked)
}
// 全选
const checkedAll = ref(false)
function selectAll(e) {
  orderDetail.value.details.forEach(item => {
    item.checked = e.target.checked
  })
}

// 提交申请
const loadingBtn = ref(false)
function clickApplyForAfterSales() {
  const urls = imgUrlList.value.map(file => file.url);
  console.log(urls, 'urls')
  const explainImg = urls.join(',');
  const selectedList = orderDetail.value.details.map(item => {
    return {
      skuId: item.skuId,
      number: item.num
    };
  });
  loadingBtn.value = true
  applyForAfterSales(
      {
        details: selectedList,
        explainImg: explainImg,
        explains: form.explains,
        orderId: orderDetail.value.id,
        reasons: form.reasons,
        serviceType: form.serviceType
      }
  ).then((res) => {
    showToast(t('afterSale.applicationIsSuccessful'))
    loadingBtn.value = false
    skipDisplay.value = true
  }).catch((err) => {
    showToast(t('afterSale.applicationFailure'))
    loadingBtn.value = false
  })
}

// 取消申请
function cancelApplication() {
  router.push({path:'/order'})
}

// 计算总退款金额
// 总价格
const totalPrice = computed(() => {
  let total = 0
  orderDetail.value.details.forEach(item => {
    total += item.num * item.price
  })
  return total
})

// 返回首页
function goToHome() {
  router.push({path:'/index'})
}

// 返回订单页面
function goToOrder() {
  router.push({path:'/afterSale'})
}

onMounted(() => {
  getDetailInfo(true)
})
</script>

<template>
  <div class="p-center">
    <div class="main-con">
      <div class="order-detail" v-if="!skipDisplay">
        <div class="top-state">
          <div class="top-l">
            <div class="order-state">
              <span>{{t('afterSale.refundAfterSale')}}</span>
            </div>
            <div class="order-id">{{t('afterSale.orderNumber')}}：{{ orderDetail.orderCode }}</div>
          </div>
        </div>
        <div class="form-box">
          <van-form
              ref="formRef"
              validate-trigger="['onSubmit']"
          >
            <div class="select-box">
              <van-field
                  v-model="currentServiceType"
                  is-link
                  readonly
                  :placeholder="!form.reason ? `${t('afterSale.serviceType')}` : ''"
                  @click="showPicker = true"
              />
            </div>
            <van-popup v-model:show="showPicker" round position="center" :style="{ padding: '16px', width: '85%' }">
              <van-picker
                  :columns="serviceTypeList"
                  :columns-field-names="serviceTypeName"
                  @cancel="showPicker = false"
                  @confirm="changeServiceType"
              />
            </van-popup>
            <div class="select-box">
              <van-field
                  v-model="form.reasons"
                  is-link
                  readonly
                  :placeholder="form.reasons"
                  @click="showReasonPicker = true"
                  result-type="file"
              />
            </div>
            <van-popup v-model:show="showReasonPicker" round position="center" :style="{ padding: '16px', width: '85%' }">
              <van-picker
                  :columns="reasonList"
                  :columns-field-names="reasonName"
                  @cancel="showReasonPicker = false"
                  @confirm="selectionReason"
              />
            </van-popup>
            <div class="explains">
              <van-field
                  v-model="form.explains"
                  rows="3"
                  autosize
                  type="textarea"
                  maxlength="100"
                  :placeholder="t('afterSale.applicationInstructionsTip')"
                  show-word-limit
              />
            </div>
            <div class="img-box">
              <h4>{{t('afterSale.uploadCredentials')}}</h4>
              <van-uploader
                  v-model="fileList"
                  multiple
                  :after-read="afterRead"
                  @delete="delImg"
              />
              <div class="number-uploads">{{t('afterSale.inAll')}}<b>{{fileList.length}}</b>{{t('afterSale.severalPiecesOf')}}<b>{{4 - fileList.length}}</b>{{t('afterSale.piece')}}</div>
            </div>
          </van-form>
        </div>
        <div class="submit-box">
          <div class="select-all checkbox">
          </div>
          <div class="money-box">
            <span>{{t('afterSale.refundAmount')}}：</span>
            <span>{{currency}}{{totalPrice}}</span>
          </div>
          <div class="ant-btn">
            <van-button class="add-btn s-btn" @click="cancelApplication">{{t('afterSale.cancel')}}</van-button>
            <van-button class="s-btn" @click="clickApplyForAfterSales" :loading="loadingBtn">{{t('afterSale.submit')}}</van-button>
          </div>
        </div>
      </div>
      <div v-else class="applyFor-success">
        <div class="applyFor-tit">{{t('afterSale.refundSuccessful')}}</div>
        <div class="applyFor-info">{{t('afterSale.submitSuccessfullyTip')}}</div>
        <div class="ant-btn">
          <van-button class="line-btn" @click="goToOrder">{{t('afterSale.viewOrder')}}</van-button>
          <van-button class="s-btn" @click="goToHome">{{t('afterSale.backToHomePage')}}</van-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.p-center {
  padding: 16px 16px 100px 16px;
  .main-con {
    .order-detail {
      .top-state {
        margin-bottom: 20px;
        display: flex;
        justify-content: space-between;

        .top-l {
          .order-state {
            font-weight: 600;
            font-size: 16px;
            color: #262626;
            margin-bottom: 4px;
          }

          .order-id {
            font-size: 12px;
            color: #8C8C8C;
            font-weight: 400;
          }
        }

        .top-r {
          display: flex;

          .del-btn {
            margin-left: 10px;
          }
        }
      }

      .listing {
        margin-top: 50px;
        margin-bottom: 30px;

        .listing-top {
          font-weight: 600;
          font-size: 16px;
          color: #262626;
          border-bottom: 1px solid #E5E5E5;
          padding-bottom: 10px;
          margin-bottom: 15px;
          .listing-left {
            .listing-tit {
            }
          }

          .listing-total {
          }

          .listing-tit {
          }
        }

        .list-product {
          .product-item {
            width: 100%;
            margin-bottom: 16px;
            padding-bottom: 16px;
            border-bottom: 1px solid #E5E5E5;
            :deep(.product-left) {
              .ant-checkbox-wrapper {
                height: min-content;

                .ant-checkbox-checked {
                  .ant-checkbox-inner {
                    background-color: #262626;;
                    border-color: #262626;
                  }
                }

                .ant-checkbox-checked:hover {
                  .ant-checkbox:after {
                    border-color: #262626;
                  }
                }

                .ant-checkbox-checked:after {
                  border-color: #262626 !important;
                }
              }

              .product-img {
                display: flex;
                margin-left: 12px;

                img {
                  width: 98px;
                  height: 110px;
                  margin-right: 12px;
                }
              }

              .product-num {
                width: 260px;
              }

              .product-amount {
                flex: 1;
                display: flex;
                flex-flow: column-reverse;
              }

              .product-info {
                color: #262626;
                font-size: 14px;
                display: flex;
                flex-flow: column;
                justify-content: space-between;

                .product-tit {
                  font-weight: 600;
                  margin-bottom: 15px;
                }

                .product-sku {
                  font-weight: 400;
                }

                .product-amount {
                  color: #666666;
                }
              }
            }
          }
        }
      }

      .logistics {
        h4 {
          font-size: 16px;
        }

        .logistics-box {
          border-radius: 2px;
          border: 1px solid #8C8C8C;
          padding: 0 24px;

          .logistics-tit {
            border-bottom: 1px solid #E5E5E5;
            display: flex;
            align-items: center;
            height: 52px;
            margin-bottom: 25px;
            color: #8C8C8C;
            font-size: 14px;
            font-weight: 400;

            b {
              color: #262626;
              font-weight: 400;
            }

            .logistics-companies {
              margin-right: 24px;
            }
          }

          .timeline {
            .circular {
              border-radius: 50%;
              padding: 0;
              border: none;
              width: 10px;
              height: 10px;

              i {
                width: 10px;
                height: 10px;
                display: block;
                background: #BFBFBF;
                border-radius: 50%;
              }
            }

            .active {
              width: 16px;
              height: 16px;
              padding: 2px;
              box-sizing: border-box;
              border: 1px solid #262626;

              i {
                background: #262626;
              }
            }

            p {
              font-weight: 400;
              font-size: 14px;
              color: #262626;
            }

            .logistical-time {
              color: #8C8C8C;
            }
          }
        }
      }

      .receipt-info {
        margin: 50px 0 32px 0;

        .receipt-box {
          display: flex;
          align-items: center;
          border-radius: 2px;
          border: 1px solid #8C8C8C;
          margin-top: 12px;
          padding: 16px 24px;
          font-size: 14px;

          .receipt-userName {
            width: 260px;
            font-weight: 600;
            color: #262626;
          }

          .receipt-address {
            color: #262626;
            font-weight: 400;

            .receipt-address-detail {
              margin-bottom: 5px;
            }
          }

          .receipt-country {
            flex: 1;
            color: #262626;
            font-weight: 400;
          }
        }
      }

      .price-breakdown {
        background: #FAFAFA;
        border-radius: 2px;
        padding: 16px;
        font-weight: 400;
        font-size: 14px;
        color: #262626;

        .flex-box {
          margin-bottom: 8px;
        }

        .amount-due {
          padding-top: 24px;
          margin-top: 16px;
          border-top: #E5E5E5 solid 1px;
        }
      }

      .form-box {
        margin-top: 0px;
        .type-service {
          .type-item {
            width: 117px;
            height: 44px;
            line-height: 44px;
            text-align: center;
            border-radius: 2px;
            border: 1px solid #8C8C8C;
            font-weight: 400;
            font-size: 14px;
            color: #8C8C8C;
            cursor: pointer;
            margin-right: 16px;
          }
          .type-item:hover, .active {
            border: 1px solid #262626;
            color: #262626;
          }
        }

        .clearfix {
          margin-bottom: 32px;
          .number-uploads {
            font-weight: 400;
            font-size: 12px;
            color: #262626;
            b {
              font-weight: 400;
              color: #E85A2B;
            }
          }
        }
      }

      .submit-box {
        position: fixed;
        bottom: 0;
        left: 0;
        width: 100%;
        .money-box {
          display: flex;
          padding: 0 10px;
          justify-content: space-between;
          font-size: 14px;
          margin: 10px 0;
          border-top: 1px solid #E5E5E5;
          padding-top: 20px;
        }
        .ant-btn {
          padding-bottom: 10px;
          display: flex;
          .s-btn {
            border: 1rpx solid #262626;
            margin: 5px 10px;
          }
        }
      }
    }
    .applyFor-success {
      text-align: center;
      padding-top: 120px;
      .applyFor-tit {
        font-size: 16px;
        color: #262626;
        font-weight: 600;
      }
      .applyFor-info {
        font-size: 14px;
        color: #8C8C8C;
        margin: 6px 0 12px 0;
      }
      .ant-btn {
        button {
          width: 120px;
          height: 44px;
          border-radius: 0;
          margin:0 6px;
        }
      }
    }
  }
}
.select-box {
  border: 1px solid #E5E5E5;
  margin-bottom: 20px;
}
.explains {
  border: 1px solid #E5E5E5;
}
.img-box {
  h4 {
    font-size: 14px;
  }
  .number-uploads {
    font-size: 12px;
    font-weight: 400;
    b {
      font-weight: 400;
      color: #E85A2B;
    }
  }
}
</style>
